from flask.app import Flask
from flask.globals import request
from flask_cors import CORS
from flask import render_template, jsonify
import json
import services
import traceback
import os
#初始化app
app = Flask(__name__, instance_relative_config=True, template_folder=os.getcwd())
CORS(app, supports_credentials=True)  # 设置允许跨域访问

def readJsonData():
    #从请求对象中读取请求的json数据
    try:
        json_data = request.get_json(force=True)#
        if json_data:
            return json_data
    except:
        traceback.print_exc()
    return {}

def ok_data(data=None):
    #返回正常的json数据
    ret = {"code": 0, "msg": "ok"}
    if data!=None and isinstance(data, dict):
        for key in data.keys():
            ret[key] = data[key]
    return jsonify(ret)

def error_data(code, msg):
    #错误的数据
    data = {"code": code, "msg": msg}
    return jsonify(data)

def msissing_parameters_error():
    #错误的参数错误
    return error_data(400, "Missing parameters.")

def illegal_access_error():
    #非法访问
    return error_data(340, "Illegal access.")

@app.route('/', methods=['GET', 'POST'])
def hello():
    #print(request.form)
    #print(request.get_data())
    return '<h1 style="color:blue">If you saw this page，indicates that it has started normally...</h1>'

@app.route('/login', methods=['GET'])
def login_page():
    #返回登录页
    return render_template('login.html')

@app.route('/main', methods=['GET'])
def mian_page():
    #返回主页
    return render_template('main.html')

#设备验证
@app.route('/device/verify',methods=['POST'])
def device_verify():
    data = readJsonData()
    key = data.get("key")
    if key:
        try:
            token = services.device_verify(key)
            return ok_data({'token': token})
        except Exception as e:
            traceback.print_exc()
            return error_data(-1, str(e))
    else:
        return msissing_parameters_error()

@app.route('/device/beat',methods=['POST'])
def device_beat():
    #设备心跳
    token = request.headers.get("token")
    if token and services.verify_device_token(token):
        try:
            data = readJsonData()
            data = services.device_beat(data)
            return ok_data(data)
        except Exception as e:
            traceback.print_exc()
            return error_data(-1, str(e))
    else:
        #print(token)
        return illegal_access_error()

@app.route('/mgr/login',methods=['POST'])
def mgr_login():
    #用户登录
    data = readJsonData()
    name = data.get("username")
    pwd = data.get("password")
    if name and pwd:
        try:
            token = services.user_login(name, pwd)
            return ok_data({'token': token})
        except Exception as e:
            traceback.print_exc()
            return error_data(-1, str(e))
    else:
        return msissing_parameters_error()

@app.route('/mgr/setled',methods=['POST'])
def mgr_setledstate():
    #设置Led状态
    token = request.headers.get("token")
    if token and services.verify_user_token(token):
        data = readJsonData()
        state = data.get("state")
        if isinstance(state, bool):
            try:
                services.set_led_state(state)
                return ok_data()
            except Exception as e:
                traceback.print_exc()
                return error_data(-1, str(e))
        else:
            return msissing_parameters_error()
    else:
        #print(token)
        return illegal_access_error()

@app.route('/mgr/getdata',methods=['POST'])
def mgr_getdata():
    #获取数据
    token = request.headers.get("token")
    if token and services.verify_user_token(token):
        data = readJsonData()
        from_time = data.get("from")
        to_time = data.get("to")
        try:
            data = services.get_device_data(from_time, to_time)
            led_state = services.get_led_state()
            return ok_data({"data":data, "led_state":led_state})
        except Exception as e:
            traceback.print_exc()
            return error_data(-1, str(e))
    else:
        #print(token)
        return illegal_access_error()


if __name__ == "__main__":
    app.run(host='0.0.0.0')